package cn.stylefeng.guns.modular.demos.mapi;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.hutool.core.bean.BeanUtil;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.auth.service.AuthService;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.demos.constant.factory.PassCheckStatusEnum;
import cn.stylefeng.guns.modular.demos.constant.factory.RealNameAuthStatusEnum;
import cn.stylefeng.guns.modular.demos.dto.BizPassCheckRequestDto;
import cn.stylefeng.guns.modular.demos.entity.BizPassCheckRequest;
import cn.stylefeng.guns.modular.demos.entity.BizPassCheckRequestDynamic;
import cn.stylefeng.guns.modular.demos.entity.BizRealNameInformation;
import cn.stylefeng.guns.modular.demos.entity.BizUploadFile;
import cn.stylefeng.guns.modular.demos.entity.BizWxUser;
import cn.stylefeng.guns.modular.demos.model.params.AcTokenTicketParam;
import cn.stylefeng.guns.modular.demos.model.params.BizBlacklistParam;
import cn.stylefeng.guns.modular.demos.model.params.BizDownloadFileParam;
import cn.stylefeng.guns.modular.demos.model.params.BizPassCheckAuditParam;
import cn.stylefeng.guns.modular.demos.model.params.BizPassCheckRequestDynamicParam;
import cn.stylefeng.guns.modular.demos.model.params.BizPassCheckRequestParam;
import cn.stylefeng.guns.modular.demos.model.params.BizRealNameInformationParam;
import cn.stylefeng.guns.modular.demos.model.params.BizWxUserParam;
import cn.stylefeng.guns.modular.demos.model.params.CmsArticleParam;
import cn.stylefeng.guns.modular.demos.model.result.AcTokenTicketResult;
import cn.stylefeng.guns.modular.demos.model.result.BizBlacklistResult;
import cn.stylefeng.guns.modular.demos.model.result.BizDownloadFileResult;
import cn.stylefeng.guns.modular.demos.model.result.BizPassCheckAuditResult;
import cn.stylefeng.guns.modular.demos.model.result.BizPassCheckRequestResult;
import cn.stylefeng.guns.modular.demos.model.result.BizRealNameInformationResult;
import cn.stylefeng.guns.modular.demos.model.result.BizWxUserResult;
import cn.stylefeng.guns.modular.demos.model.result.CmsArticleResult;
import cn.stylefeng.guns.modular.demos.service.AcTokenTicketService;
import cn.stylefeng.guns.modular.demos.service.BizBlacklistService;
import cn.stylefeng.guns.modular.demos.service.BizDownloadFileService;
import cn.stylefeng.guns.modular.demos.service.BizPassCheckAuditService;
import cn.stylefeng.guns.modular.demos.service.BizPassCheckRequestDynamicService;
import cn.stylefeng.guns.modular.demos.service.BizPassCheckRequestService;
import cn.stylefeng.guns.modular.demos.service.BizRealNameInformationService;
import cn.stylefeng.guns.modular.demos.service.BizUploadFileService;
import cn.stylefeng.guns.modular.demos.service.BizWxUserService;
import cn.stylefeng.guns.modular.demos.service.CmsArticleService;
import cn.stylefeng.guns.modular.demos.util.GeneratorUtil;
import cn.stylefeng.guns.modular.demos.util.SHAUtil;
import cn.stylefeng.guns.modular.demos.wrapper.BizPassCheckRequestDynamicWrapper;
import cn.stylefeng.guns.modular.demos.wrapper.BizPassCheckRequestWrapper;
import cn.stylefeng.guns.modular.demos.wrapper.CmsArticleWrapper;
import cn.stylefeng.guns.sys.modular.system.entity.Dict;
import cn.stylefeng.guns.sys.modular.system.entity.DictType;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.model.UserDto;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.guns.sys.modular.system.service.DictTypeService;
import cn.stylefeng.guns.sys.modular.system.service.RoleService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.RequestEmptyException;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import cn.stylefeng.roses.kernel.model.response.SuccessResponseData;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

@Slf4j
@Controller
@RequestMapping("/rest")
public class BizWxApiController extends BaseController {

	//private String dirverRoleId = "6";
	//private String policeRoleId = "7";
	//private Long driverDefaultDept = 25L;
	
	@Value("${zdcl.upimg}")
	private String upimgPath;
	
	@Value("${zdcl.dirverRoleId}")
	private Long dirverRoleId;
	
	@Value("${zdcl.policeRoleId}")
	private Long policeRoleId;
	
	@Value("${zdcl.driverDeptId}")
	private Long driverDeptId;
	
	@Value("${zdcl.wxAcTokenFrom}")
	private String wxAcTokenFrom;  //default otherDb
	

	
	private String carTypeDictCode = "SYS_ZDCL_CAR_TYPE";
	private String passTypeDictCode = "SYS_ZDCL_PASS_TYPE";
	private String auditStatusTypeDictCode = "SYS_ZDCL_AUDIT_STATUS";
	private String entTownAddrTypeDictCode = "SYS_ZDCL_ENT_TOWN_ADDR";
	
	private String textFileTypeDictCode = "1";
	private String imageFileTypeDictCode = "2";
	private String officeFileTypeDictCode = "3";
	private String videoFileTypeDictCode = "4";
	private String pdfFileTypeDictCode = "5";
	private String userUploadFileTypeDictCode = "101";
	
	private int passUnCheckStatus = 2;
	
	@Autowired
	private WxMpService wxService;
	 
	@Resource
	private AuthService authService;
	
    @Autowired
    private UserService userService;
	
	@Autowired
    private BizWxUserService bizWxUserService;
	
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private DictService dictService;
    
    @Autowired
    private DictTypeService dictTypeService;
    
	

    @Autowired
    private BizRealNameInformationService bizRealNameInformationService;
	
    @Autowired
    private BizPassCheckRequestService bizPassCheckRequestService;
    
    @Autowired
    private BizUploadFileService bizUploadFileService;
    
    @Autowired
    private BizPassCheckRequestDynamicService bizPassCheckRequestDynamicService;
    
    @Autowired
    private AcTokenTicketService acTokenTicketService;
    
    @Autowired
    private BizPassCheckAuditService bizPassCheckAuditService;
	
    
    @Autowired
    private BizDownloadFileService bizDownloadFileService;
    
    @Autowired
    private CmsArticleService cmsArticleService;
    
    @Autowired
    private BizBlacklistService bizBlacklistService;
    
    
    
    
    /**
     * 微信授权登录 h5
     * 
     * 返回系统关联用户信息 和 h5 jsApi Signature
     *
     * @author zjj
     * @Date 2020-08-13
     */
    @RequestMapping("/wxLogin")
    @ResponseBody
    public ResponseData wxLogin(String appid, String code,String url) {
    	Map<String,Object> result = new HashMap();
    	boolean isPolice = false;
	    
    	 log.info("appid:{}",appid);
    	//url = "http://www.dogroot.com/zdcl-wx/mh5/index.html";
    	//
    	if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
    	
    	try {
              WxMpOAuth2AccessToken accessToken = wxService.oauth2getAccessToken(code);
              log.info("accessToken={}", JSON.toJSONString(accessToken));
              //accessToken={
//              	"accessToken":"36_4vfPEgDejjENQsb6JUvkM_s-FMbqiU5uX_pUAYiSGxGuDwCutfBviD1eefLRjkY-zRipJnbS7x_hpZNA1qYI2w",
//              	"expiresIn":7200,
//              	"openId":"oAkVxt0kxOBPvUyoJWc-y8G2qgxo",
//              	"refreshToken":"36_qNL7R2mhOW7kU165tqDj3lrnf0-d8PhFdIVaCvS9STxeiwS3-L31TWKoqHq5vlSroyYINLXI5OYHBKX2wsL7eA",
//              	"scope":"snsapi_userinfo"
//              }
 
          	  //result.put("wxAccessToken",accessToken);
              log.info("url:{}",url);
              if("otherDb".equals(wxAcTokenFrom)) {
            		List<AcTokenTicketResult>  actList = acTokenTicketService.findListBySpec(new AcTokenTicketParam());
            		try {
	            		log.info("acToken id:{} , expTime: {} token:{}  jsApiTicket: {}",
	            				actList.get(0).getId(),
	            				actList.get(0).getExpireTime(),
	            				actList.get(0).getAccessToken(),
	            				actList.get(0).getJsapiTicket());
	            		
	            		String wxH5Ticket = actList.get(0).getJsapiTicket();
	            		//String wxH5Ticket = SHAUtil.getWxH5Ticket(actList.get(0).getAccessToken());
	            		String noncestr = GeneratorUtil.genUUId();
	            		String timestamp = Long.toString(System.currentTimeMillis()/1000);
	                    StringBuilder sb = new StringBuilder();
	                    sb.append("jsapi_ticket=");
	                    sb.append(wxH5Ticket);
	                    sb.append("&noncestr=");
	                    sb.append(noncestr);
	                    sb.append("&timestamp=");
	                    sb.append(timestamp);
	                    sb.append("&url=");
	                    sb.append(url);
	                    //明文
	                    String content = sb.toString();
	                    String signature = SHAUtil.shaEncode(content);
	                    
						log.info("content:{}",content);
						log.info("signature:{}",signature);
						
	                    Map<String, Object> wxJsapiSignature = new HashMap<>();
	                    wxJsapiSignature.put("nonceStr", noncestr);
	                    wxJsapiSignature.put("timestamp", timestamp);
	                    wxJsapiSignature.put("signature", signature);
	                    wxJsapiSignature.put("appId", appid);
	                    
	                    result.put("wxJsapiSignature", wxJsapiSignature);
            		} catch (Exception e) {
						// TODO Auto-generated catch block
            			
						e.printStackTrace();
					}
              }else {
            	  WxMpUser user = wxService.oauth2getUserInfo(accessToken, null);
                  log.info("wxMpUser={}", JSON.toJSONString(user));
                  //如果不需要调用wx jsAPi  可以省略
                  WxJsapiSignature  wxJsapiSignature = wxService.createJsapiSignature(url);
                  log.info("wxJsapiSignature={}", JSON.toJSONString(wxJsapiSignature));
                  //wxJsapiSignature={"appId":"wx8e998a2e897d6805","nonceStr":"j6qnlI5CWXIG9Tjw","signature":"c41d20ab37fd4b761b07056350c6be168a47318a","timestamp":1598155546}
                  // String getJsapiTicket = wxService.getJsapiTicket();
                  // log.info("getJsapiTicket={}", getJsapiTicket);
                  result.put("wxJsapiSignature", wxJsapiSignature);
              }
              
              
              Long sysUserId = null;
              Long wxUserId = null;
              
              ///
              BizWxUserParam param = new BizWxUserParam();
              param.setWxOpenId(accessToken.getOpenId());
             
              
              BizWxUserResult  bizWxUser = bizWxUserService.findBySpec(param);
              if(bizWxUser == null) {
              	BizWxUser entity = new BizWxUser();
              	entity.setWxOpenId(accessToken.getOpenId());
              	bizWxUserService.saveOrUpdate(entity);
              	bizWxUser = bizWxUserService.findBySpec(param);
              }
    
              //微信登录默认不是系统用户
              result.put("sysUser",false);
              result.put("realNameAuth",false);
              sysUserId = bizWxUser.getUserId();
              wxUserId = bizWxUser.getId();
              
              result.put("wxUserId", wxUserId);
              
              
              if(sysUserId!=null) {
            	   try {
						User sysUser = userService.getById(bizWxUser.getUserId());
						if(sysUser!=null) {
						  	String token = authService.login(sysUser.getAccount());
						  
						  	//获取角色
							String roleIds = sysUser.getRoleId();
							String[] roleIdArr = roleIds.split(",");
							String roles = "";
							for(String id : roleIdArr) {
								roles += roleService.getById(String.valueOf(id)).getDescription();
								if(roles.indexOf("police")>=0) {
							  			isPolice = true;
							  		}
							 }
							result.put("sysUser",true);
							result.put("roles",roles);
							result.put("token",token);
							result.put("realName",sysUser.getName());
							result.put("phone",sysUser.getPhone());
							
							//关联实名认证情况
							BizRealNameInformationParam realParam = new BizRealNameInformationParam();
							realParam.setUserId(sysUser.getUserId());
							BizRealNameInformationResult realResult = bizRealNameInformationService.findBySpec(realParam);
							if(realResult!=null && 
							    		(realResult.getStatus().intValue() == RealNameAuthStatusEnum.unCheck.intValue() ||
							    		realResult.getStatus().intValue() == RealNameAuthStatusEnum.checkSuccess.intValue())
							    	) {
								result.put("realNameAuth",true);
							}
						}
            	   }catch(Exception e) {
            		   log.error(e.toString());
            		   e.printStackTrace();
            	   }
              }
    	 } catch (WxErrorException e) {
    		  log.error(e.toString());
              e.printStackTrace();
         }
    	
    	if(isPolice) {
	    	result.put("realNameAuth",true);
	    }
    	
    	
    	
        return ResponseData.success(result);
    }
    
	/**
	 * 绑定登录
	 *   wxUserId  存在则 绑定微信用户
	 *
	 * @author zjj
	 * @Date 2018/12/23 5:42 PM
	 */
	@RequestMapping(value = "/bindLogin", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData policeLogin() {
		Map<String,Object> result = new HashMap();
		boolean isPolice = false;
		     
	    String wxUserId = super.getPara("wxUserId");
	    String password = super.getPara("password");
	    String username = super.getPara("username");
	
	    if (ToolUtil.isOneEmpty(password,username)) {
	        throw new RequestEmptyException("账号或密码为空！");
	    }
	    
	    User sysUser = userService.getByAccount(username);
	    if(sysUser==null) {
	    	 throw new RequestEmptyException("账号不存在！");
	    }
	    
	    
        //登录并创建token
        String token = authService.login(username, password);
        result.put("token",token);
    	//获取角色
      	String roleIds = sysUser.getRoleId();
      	String[] roleIdArr = roleIds.split(",");
      	String roles = "";
      	for(String id : roleIdArr) {
      		roles += roleService.getById(String.valueOf(id)).getDescription();
      		if(roles.indexOf("police")>=0) {
      			isPolice = true;
      		}
      	}
      
      	result.put("sysUser",true);
      	result.put("roles",roles);
     	result.put("realName",sysUser.getName());
	    result.put("phone",sysUser.getPhone());
	    

	    if(wxUserId != null && !"".equals(wxUserId)) {
	    	 BizWxUser  bizWxUser = bizWxUserService.getById(Long.parseLong(wxUserId));        
	    	 if(bizWxUser!=null) {
		    	 bizWxUser.setUserId(sysUser.getUserId());
		         bizWxUserService.saveOrUpdate(bizWxUser);
	    	 }
	    }
	    
	    //关联实名认证情况
	    BizRealNameInformationParam realParam = new BizRealNameInformationParam();
	    realParam.setUserId(sysUser.getUserId());
	    BizRealNameInformationResult realResult = bizRealNameInformationService.findBySpec(realParam);
	    if(realResult!=null && 
	    		(realResult.getStatus().intValue() == RealNameAuthStatusEnum.unCheck.intValue() ||
	    		realResult.getStatus().intValue() == RealNameAuthStatusEnum.checkSuccess.intValue())
	    	) {
	    	result.put("realNameAuth",true);
	    }else {
	    	result.put("realNameAuth",false);
	    }
        
		if(isPolice) {
	    	result.put("realNameAuth",true);
	    }
		
//		List<AcTokenTicketResult>  actList = acTokenTicketService.findListBySpec(new AcTokenTicketParam());
//		log.info("acToken id{} , expTime: {} token:{}  jsApiTicket: {}",
//				actList.get(0).getId(),
//				actList.get(0).getExpireTime(),
//				actList.get(0).getAccessToken(),
//				actList.get(0).getJsapiTicket()
//				);
//		
        return new SuccessResponseData(result);
	}
	
	/**
	 * 绑定注册
	 *   wxUserId  存在则  绑定微信用户
	 * @author zjj
	 * @Date 2018/12/23 5:42 PM
	 */
	@RequestMapping(value = "/bindRegister", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData driverRegister() {
		 UserDto user = new UserDto();
		 boolean isPolice = false;
	     
		
		 //1 取输入信息
		 String wxUserId = super.getPara("wxUserId");
		 String realName = super.getPara("realName");
		 String phone = super.getPara("phone");
		 String password = super.getPara("password");
		 
		 
		 if (ToolUtil.isOneEmpty(password,realName)) {
		        throw new RequestEmptyException("账号或密码为空！");
		 }
		 
		 if (ToolUtil.isOneEmpty(phone)) {
		        throw new RequestEmptyException("手机号为空！");
		 }
		 
		 //查询角色ID
		 
		 //2 创建系统账户  手机号默认为登录用户名
		 User sysUser = userService.getByAccount(phone);
		 if(sysUser==null) {
			 user.setAccount(phone);
			 user.setPassword(password);
			 user.setPhone(phone);
			 user.setName(realName);
			 user.setSex("M");
			 user.setDeptId(driverDeptId);
			 //默认司机角色
			 user.setRoleId(dirverRoleId.toString());
			 //
			 this.userService.addUser(user);
			 sysUser = userService.getByAccount(phone);
		 }
		 if(sysUser==null) {
	    	 throw new RequestEmptyException("账号不存在！phone:"+phone);
	     }
		 
//		 //
//		 //3 创建用户实名信息
//		 BizRealNameInformationParam info = new BizRealNameInformationParam();
//		 info.setUserId(sysUser.getUserId());
//		 info.setUserName(realName);
//		 info.setStatus(1);
//		 bizRealNameInformationService.add(info);
	     Map<String,Object> result = new HashMap();
	 	 String token = authService.login(sysUser.getAccount(),password);
    	 result.put("token",token);
    	 //获取角色
         String roleIds = sysUser.getRoleId();
       	 String[] roleIdArr = roleIds.split(",");
       	 String roles = "";
       	 for(String id : roleIdArr) {
      		roles += roleService.getById(String.valueOf(id)).getDescription();
      		if(roles.indexOf("police")>=0) {
      			isPolice = true;
      		}
      	 }
    	 result.put("roles",roles);
       	 result.put("sysUser",true);
    	 result.put("realName",sysUser.getName());
    	 result.put("phone",sysUser.getPhone());
    	 
    	 //4 关联微信用户
		 if(wxUserId!=null && !"".equals(wxUserId)) {
			 BizWxUser bizWxUser = bizWxUserService.getById(Long.parseLong(wxUserId)); 
			 if(bizWxUser != null) {
				 bizWxUser.setUserId(sysUser.getUserId());
			     bizWxUserService.saveOrUpdate(bizWxUser);
			 }
		 }
		 
		//关联实名认证情况
	    BizRealNameInformationParam realParam = new BizRealNameInformationParam();
	    realParam.setUserId(sysUser.getUserId());
	    BizRealNameInformationResult realResult = bizRealNameInformationService.findBySpec(realParam);
	    if(realResult!=null && 
	    		(realResult.getStatus().intValue() == RealNameAuthStatusEnum.unCheck.intValue() ||
	    		realResult.getStatus().intValue() == RealNameAuthStatusEnum.checkSuccess.intValue())
	    	) {
	    	result.put("realNameAuth",true);
	    }else {
	    	result.put("realNameAuth",false);
	    }
		if(isPolice) {
	    	result.put("realNameAuth",true);
	    }
		return new SuccessResponseData(result);
	}
	
	/**
	 * 实名认证表单
	 * 
	 * @author zjj
	 * @Date 2018/12/23 5:42 PM
	 */
	@RequestMapping(value = "/realNameAuth", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData realNameAuth( BizRealNameInformationParam param ) {
		BizRealNameInformation entity = new BizRealNameInformation();
		
   	     //判断用户角色司机用户只能获取自己相关的记录
   	    //获取当前用户角色列表
        LoginUser user = LoginContextHolder.getContext().getUser();
        //List<Long> roleList = user.getRoleList();
        if(user==null) {
        	return ResponseData.error("系统用户异常");
        }
		
        //避免重复插入数据
        BizRealNameInformationParam rniParam = new BizRealNameInformationParam();
        rniParam.setUserId(user.getId());
        rniParam.setUserIdOperator("eq");
        BizRealNameInformationResult rniResult = bizRealNameInformationService.findBySpec(rniParam);
        if(rniResult!=null) {
        	BeanUtil.copyProperties(rniResult, entity);
        }
        
        if(param.getUserName()!=null) {
        	entity.setUserName(param.getUserName());
        }
        if(param.getIdCard()!=null) {
        	entity.setIdCard(param.getIdCard());
        }
        if(param.getIdCardFront()!=null) {
        	entity.setIdCardFront(param.getIdCardFront());
        }
        if(param.getIdCardReverse()!=null) {
        	entity.setIdCardReverse(param.getIdCardReverse());
        }
        //修改信息后需要重新认证
        entity.setStatus(RealNameAuthStatusEnum.unCheck);
        entity.setUserId(user.getId());
		bizRealNameInformationService.saveOrUpdate(entity);
		
		return ResponseData.success();
	}
	

	/**
	 * 获取业务相关字典信息
	 *
	 * @author fengshuonan
	 * @Date 2018/12/23 5:42 PM
	 */
	@RequestMapping(value = "/getBizDicts", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData getBizDicts() {
		Map<String,Object> result = new HashMap();
		
		ArrayList<Map<String, Object>> catTypeDictsMap = new ArrayList<>();
		ArrayList<Map<String, Object>> passTypeDictsMap = new ArrayList<>();
		ArrayList<Map<String, Object>> asTypeDictsMap = new ArrayList<>();
		ArrayList<Map<String, Object>> entTownTypeDictsMap = new ArrayList<>();
		

		DictType typeDict = dictTypeService.getDictTypeByCode(carTypeDictCode);
		if(typeDict!=null) {
			List<Dict> dicts = dictService.listDicts(typeDict.getDictTypeId());
			for (Dict dict : dicts) {
				Map<String, Object> map = BeanUtil.beanToMap(dict);
				catTypeDictsMap.add(map);
			}
		}
		
		typeDict = dictTypeService.getDictTypeByCode(passTypeDictCode);
		if(typeDict!=null) {
			List<Dict> dicts = dictService.listDicts(typeDict.getDictTypeId());
			for (Dict dict : dicts) {
				Map<String, Object> map = BeanUtil.beanToMap(dict);
				passTypeDictsMap.add(map);
			}
		}
		
		typeDict = dictTypeService.getDictTypeByCode(auditStatusTypeDictCode);
		if(typeDict!=null) {
			List<Dict> dicts = dictService.listDicts(typeDict.getDictTypeId());
			for (Dict dict : dicts) {
				Map<String, Object> map = BeanUtil.beanToMap(dict);
				asTypeDictsMap.add(map);
			}
		}
		
		typeDict = dictTypeService.getDictTypeByCode(entTownAddrTypeDictCode);
		if(typeDict!=null) {
			List<Dict> dicts = dictService.listDicts(typeDict.getDictTypeId());
			for (Dict dict : dicts) {
				Map<String, Object> map = BeanUtil.beanToMap(dict);
				entTownTypeDictsMap.add(map);
			}
		}
		
		
		
		result.put("carTypeDict", catTypeDictsMap);
		result.put("passTypeDict", passTypeDictsMap);
		result.put("entTownTypeDict", entTownTypeDictsMap);
		//result.put("audStatusTypeDict", asTypeDictsMap);
		
		return ResponseData.success(result);
	}
	
	
	
	/**
	 * 司机用户提交通行证申请
	 *
	 * @author fengshuonan
	 * @Date 2018/12/23 5:42 PM
	 */
	@RequestMapping(value = "/passApply", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData passApply(BizPassCheckRequestDto bizPassCheckRequestDto) {

		
		BizPassCheckRequest entity = new BizPassCheckRequest();
		ToolUtil.copyProperties(bizPassCheckRequestDto, entity);
		
		//默认状态为待审核
		entity.setPassCheckStatus(passUnCheckStatus);
		this.bizPassCheckRequestService.saveOrUpdate(entity);
		
		
		log.debug("new passApply id:"+entity.getId().toString());
		Map<String,Object> result = new HashMap(); 
		result.put("passCheckRequestId", entity.getId().toString());
		
		String allPicsJson = bizPassCheckRequestDto.getAllPicsJson();
		JSONArray jsonArr = JSONObject.parseArray(allPicsJson);
		
		for(int i= 0;i<jsonArr.size();i++) {
			//BizPassCheckRequestPicsDto picDto = allPics[i];
			BizPassCheckRequestDynamic dynamicEntity = new BizPassCheckRequestDynamic();
			JSONObject json = jsonArr.getJSONObject(i);
			
			dynamicEntity.setSort(json.getInteger("sort"));
			dynamicEntity.setFieldType(json.getString("fieldType"));
			dynamicEntity.setFieldName(json.getString("fieldName"));
			dynamicEntity.setFieldCnName(json.getString("fieldCnName"));
			dynamicEntity.setFieldValue(json.getString("fieldValue"));

			dynamicEntity.setPassCheckRequestId(entity.getId());
	        bizPassCheckRequestDynamicService.saveOrUpdate(dynamicEntity);
	        
		}
		
        
	    return ResponseData.success(result);
	}
	
	@RequestMapping(value="/passUpload", method=RequestMethod.POST)
	@ResponseBody
	public ResponseData passUpload(@RequestParam("file") MultipartFile file, 
			HttpServletRequest request){
		   
			HashMap<String, Object> result = new HashMap<>();
	        String suffixName = null;
	        String newPath = "";
	        String newName = "";
	        String originFileName = "";
	        
	        String fileDescribe = super.getPara("fileDescribe");
	    
	        Date curDate = new Date();
	        
	        newPath+=curDate.getYear()+1900;
	        newPath += "/";
	        newPath += (curDate.getMonth() +1)< 10 ? "0"+(curDate.getMonth() +1) : (curDate.getMonth()+1);
	        newPath += "/";
	        newPath += curDate.getDate() < 10 ? "0"+curDate.getDate() : curDate.getDate();
	        newPath += "/";
	        newPath += curDate.getHours()< 10 ? "0"+curDate.getHours() : curDate.getHours();
	        newPath += "/";
	        // 文件名
	        try{
	        	originFileName = file.getOriginalFilename();
		        log.debug("文件名： " + originFileName);
	
		        // 文件后缀
		        suffixName = originFileName.substring(originFileName.lastIndexOf("."));
		        log.debug("文件后缀名： " + suffixName);
	        }catch(Exception e){
	        	// return new ResponseEntity<>("上传失败", HttpStatus.SERVICE_UNAVAILABLE);
	        	return ResponseData.error("上传失败");
	        }

	        
	        // 重新生成唯一文件名，用于存储数据库
	        String uuid = UUID.randomUUID().toString();
	        newName += (uuid+suffixName);
	        System.out.println("新的文件名： " + newName);
	        
	        //创建文件
	        File dest = new File(upimgPath + newPath+newName);
	        //路径不存在创建路径
	        File fileParent = dest.getParentFile();  
	        if(!fileParent.exists()){  
	            fileParent.mkdirs();  
	        }  

	        try {
	            file.transferTo(dest);
	            //
	            BizUploadFile fileEntity =new BizUploadFile();
	            fileEntity.setFilePath(newPath+newName);
	            fileEntity.setOriginFileName(originFileName);
	            fileEntity.setGuid(uuid);
	            fileEntity.setSuffix(suffixName);
	            if(suffixName.indexOf("jpg")>=0 ||
	            		suffixName.indexOf("png")>=0 ||
	            		suffixName.indexOf("bmp")>=0 ||
	            		suffixName.indexOf("JPG")>=0 ||
	            		suffixName.indexOf("JPEG")>=0
	            		) {
		            fileEntity.setFileType(imageFileTypeDictCode);
	            }else if (suffixName.indexOf("doc")>=0 ||
	            		suffixName.indexOf("docx")>=0 ||
	            		suffixName.indexOf("xlsx")>=0 ||
	            		suffixName.indexOf("ppt")>=0
	            		 ){
	            	fileEntity.setFileType(officeFileTypeDictCode);
	            }else if (suffixName.indexOf("mp4")>=0 ||
	            		suffixName.indexOf("avi")>=0
	            		){
	            	fileEntity.setFileType(videoFileTypeDictCode);
	            }else if (suffixName.indexOf("pdf")>=0
	            		){
	            	fileEntity.setFileType(pdfFileTypeDictCode);
	            }
	            if(fileDescribe==null || "".equals(fileDescribe)) {
	            	 fileEntity.setFileDescribe("未知");
	            }else {
	            	 fileEntity.setFileDescribe(fileDescribe);
	            }
	            
	            bizUploadFileService.saveOrUpdate(fileEntity);
	            
	            result.put("id", fileEntity.getId());
	            //result.put("msg", "上传成功");
	            
	            //return new ResponseEntity<>(urlPath, HttpStatus.OK);
	            return ResponseData.success(result);
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        
	        return ResponseData.error("上传失败");
	       // return new ResponseEntity<>(urlPath, HttpStatus.SERVICE_UNAVAILABLE);
	}
	
	

//	@RequestMapping(value="/passUpload", method=RequestMethod.POST)
//	public ResponseEntity upload(@RequestParam("file") MultipartFile file, 
//			HttpServletRequest request){
//	        String suffixName = null;
//	        String newPath = "";
//	        String newName = "";
//	        String originFileName = "";
//	        
//
//	        String passCheckRequestIdStr = super.getPara("passCheckRequestId");
//	        String fieldType = super.getPara("fieldType");
//	        String fieldName = super.getPara("fieldName");
//	        String fieldCnName = super.getPara("fieldCnName");
//	        String seq = super.getPara("seq");
//	        
//	        
//	        log.debug("passCheckRequestIdStr:"+passCheckRequestIdStr);
//	        log.debug("fieldType:"+fieldType);
//	        log.debug("fieldName:"+fieldName);
//	        log.debug("fieldCnName:"+fieldCnName);
//	        log.debug("seq:"+seq);
//	        
//	        if(passCheckRequestIdStr == null || passCheckRequestIdStr.equals("")) {
//	        	return new ResponseEntity<>("参数异常",HttpStatus.BAD_REQUEST);
//	        }
//	        
//	        if(fieldType == null || fieldType.equals("")) {
//	        	return new ResponseEntity<>("参数异常",HttpStatus.BAD_REQUEST);
//	        }
//	        
//	        if(fieldName == null || fieldName.equals("")) {
//	        	return new ResponseEntity<>("参数异常",HttpStatus.BAD_REQUEST);
//	        }
//	        
//	        if(fieldCnName == null || fieldCnName.equals("")) {
//	        	return new ResponseEntity<>("参数异常",HttpStatus.BAD_REQUEST);
//	        }
//	        
//	        if(seq == null || seq.equals("")) {
//	        	return new ResponseEntity<>("参数异常",HttpStatus.BAD_REQUEST);
//	        }
//	        
//	        
//	        HashMap<String, Object> urlPath = new HashMap<>();
//	        Date curDate = new Date();
//	        
//	        newPath+=curDate.getYear()+1900;
//	        newPath += "/";
//	        newPath += (curDate.getMonth() +1)< 10 ? "0"+(curDate.getMonth() +1) : (curDate.getMonth()+1);
//	        newPath += "/";
//	        newPath += curDate.getDate() < 10 ? "0"+curDate.getDate() : curDate.getDate();
//	        newPath += "/";
//	        newPath += curDate.getHours()< 10 ? "0"+curDate.getHours() : curDate.getHours();
//	        newPath += "/";
//	        // 文件名
//	        try{
//	        	originFileName = file.getOriginalFilename();
//		        log.debug("文件名： " + originFileName);
//	
//		        // 文件后缀
//		        suffixName = originFileName.substring(originFileName.lastIndexOf("."));
//		        log.debug("文件后缀名： " + suffixName);
//	        }catch(Exception e){
//	        	 return new ResponseEntity<>("上传失败", HttpStatus.SERVICE_UNAVAILABLE);
//	        }
//
//	        
//	        // 重新生成唯一文件名，用于存储数据库
//	        String uuid = UUID.randomUUID().toString();
//	        newName += (uuid+suffixName);
//	        System.out.println("新的文件名： " + newName);
//	        
//	        //创建文件
//	        File dest = new File(upimgPath + newPath+newName);
//	        //路径不存在创建路径
//	        File fileParent = dest.getParentFile();  
//	        if(!fileParent.exists()){  
//	            fileParent.mkdirs();  
//	        }  
//
//	        try {
//	            file.transferTo(dest);
//	            urlPath.put("urlPath", newPath);
//	            urlPath.put("msg", "上传成功");
//	            
//	            //
//	            BizUploadFile fileEntity =new BizUploadFile();
//	            fileEntity.setFilePath(newPath+newName);
//	            fileEntity.setOriginFileName(originFileName);
//	            fileEntity.setGuid(uuid);
//	            fileEntity.setSuffix(suffixName);
//	            if(suffixName.indexOf("jpg")>=0 ||
//	            		suffixName.indexOf("png")>=0 ||
//	            		suffixName.indexOf("bmp")>=0 ||
//	            		suffixName.indexOf("JPG")>=0 ||
//	            		suffixName.indexOf("JPEG")>=0
//	            		) {
//		            fileEntity.setFileType(imageFileTypeDictCode);
//	            }else if (suffixName.indexOf("doc")>=0 ||
//	            		suffixName.indexOf("docx")>=0 ||
//	            		suffixName.indexOf("xlsx")>=0 ||
//	            		suffixName.indexOf("ppt")>=0
//	            		 ){
//	            	fileEntity.setFileType(officeFileTypeDictCode);
//	            }else if (suffixName.indexOf("mp4")>=0 ||
//	            		suffixName.indexOf("avi")>=0
//	            		){
//	            	fileEntity.setFileType(videoFileTypeDictCode);
//	            }else if (suffixName.indexOf("pdf")>=0
//	            		){
//	            	fileEntity.setFileType(pdfFileTypeDictCode);
//	            }
//	            
//	            fileEntity.setFileDescribe(fieldCnName);
//	            bizUploadFileService.saveOrUpdate(fileEntity);
//	            
//	            BizPassCheckRequestDynamic passEntity = new BizPassCheckRequestDynamic();
//	            
//	            passEntity.setPassCheckRequestId(Long.parseLong(passCheckRequestIdStr));
//	            passEntity.setFieldType(fieldType);
//	            passEntity.setFieldName(fieldName);
//	            passEntity.setFieldCnName(fieldCnName);
//	            passEntity.setFieldValue(fileEntity.getId().toString());
//	            passEntity.setSort(Integer.valueOf(seq).intValue());
//	            bizPassCheckRequestDynamicService.saveOrUpdate(passEntity);
//	            
//	            
//	            return new ResponseEntity<>(urlPath, HttpStatus.OK);
//	        } catch (IOException e) {
//	            e.printStackTrace();
//	        }
//	        urlPath.put("msg", "上传失败");
//	        return new ResponseEntity<>(urlPath, HttpStatus.SERVICE_UNAVAILABLE);
//	}
	

    /**
     * 查看详情接口
     *
     * @author zjj
     * @Date 2020-08-13
     */
    @RequestMapping("/passInfo")
    @ResponseBody
    public ResponseData passInfo(BizPassCheckRequestParam bizPassCheckRequestParam) {
    	BizPassCheckRequest detail = null;
    	//两种参数查询方式
    	if(bizPassCheckRequestParam.getId() != null) {
    		 detail = this.bizPassCheckRequestService.getById(bizPassCheckRequestParam.getId());
    	}else if(bizPassCheckRequestParam.getPassCheckNum() != null) {
    		BizPassCheckRequestResult result = this.bizPassCheckRequestService.findBySpec(bizPassCheckRequestParam);
    		if(result!=null) {
    			detail = new BizPassCheckRequest();
    			BeanUtil.copyProperties(result, detail);
    		}
    	}
    	
    	if(detail==null) {
    		 return ResponseData.error("没有查询到结果");
    	}
    	
        List<Map<String, Object>>  dynamic = new ArrayList<>();
        
        
        BizPassCheckRequestDynamicParam dynamicParam = new BizPassCheckRequestDynamicParam();
        dynamicParam.setPassCheckRequestId(detail.getId());
        dynamicParam.setPassCheckRequestIdOperator("eq");
        List<Map<String, Object>>  dynamicMaps = bizPassCheckRequestDynamicService.findMapListBySpec(dynamicParam);
       
        for (Map<String, Object> m : dynamicMaps) {
        	Map<String, Object> wrapped = new BizPassCheckRequestDynamicWrapper(m).wrap();
        	dynamic.add(wrapped);
        }
        
        Map<String,Object> result = new HashMap(); 
        
        
        Map<String, Object> detailMap = BeanUtil.beanToMap(detail);
        Map<String, Object> detailMapWrapped = new BizPassCheckRequestWrapper(detailMap).wrap();
        
        result.put("detail", detailMapWrapped);
        result.put("dynamic", dynamic);
        
        Long passCheckFileId = detail.getPassCheckFileId();
        if(passCheckFileId!=null) {
        	BizUploadFile passCheckFile = bizUploadFileService.getById(passCheckFileId);
        	result.put("passCheckFile", passCheckFileId);
        }
        
        Long passCheckImgFileId = detail.getPassCheckImgFileId();
        if(passCheckImgFileId!=null) {
        	BizUploadFile passCheckImgFile = bizUploadFileService.getById(passCheckImgFileId);
        	result.put("passCheckImgFile", passCheckImgFile);
        }
        
        
        //交警审批操作取最后一次 显示
        if(detail.getPassCheckStatus().intValue() >= PassCheckStatusEnum.fristCheck.intValue()) {
        	  BizPassCheckAuditParam pcaParam = new BizPassCheckAuditParam();
             
        	  pcaParam.setPassCheckRequestId(detail.getId());
        	  pcaParam.setAuditCategoryCodeOrder("DESC");
        	  List<BizPassCheckAuditResult> pcaList =  bizPassCheckAuditService.findListBySpec2(pcaParam);
        	  if(pcaList.size()>0) {
        		  BizPassCheckAuditResult pac = pcaList.get(0);
        		  detailMapWrapped.put("auditRemark", pac.getRemark());
        	  }
        }
      
        return ResponseData.success(result);
    }

    /**
     * 查询列表
     *
     * @author zjj
     * @Date 2020-08-13
     */
    @ResponseBody
    @RequestMapping("/passQuery")
    public LayuiPageInfo list(BizPassCheckRequestParam bizPassCheckRequestParam) {
    	
    	 //过滤删除的信息
    	 bizPassCheckRequestParam.setDelFlag(0);
    	 bizPassCheckRequestParam.setDelFlagOperator("eq");
    	 
    	 //判断用户角色司机用户只能获取自己相关的记录
    	 //获取当前用户角色列表
         LoginUser user = LoginContextHolder.getContext().getUser();
         List<Long> roleList = user.getRoleList();

         //如果角色为空
         if (roleList == null || roleList.size() == 0) {
        	 log.error("invlaid cur user role:"+user.getName());
        	 LayuiPageFactory.defaultPage();
         }
         
         for(int i=0;i<roleList.size();i++) {
        	 if(roleList.get(i).longValue()  == dirverRoleId.longValue()) {
        		 bizPassCheckRequestParam.setCreateUser(user.getId());
        		 bizPassCheckRequestParam.setCreateUserOperator("eq");
        		 break;
        	 }
         }
    	 
         
    	 Page<Map<String, Object>> page = this.bizPassCheckRequestService.findPageMapListBySpec(bizPassCheckRequestParam);
    	 
    	 Page pageWrapped = new BizPassCheckRequestWrapper(page).wrap();
    	 
    	 return LayuiPageFactory.createPageInfo(pageWrapped);
        //return this.bizPassCheckRequestService.findPageBySpec(bizPassCheckRequestParam);
    }
    
    /**
     * 查询所有的下载文件
     *
     * @author zjj
     * @Date 2020-08-13
     */
    @ResponseBody
    @RequestMapping("/downloadFiles")
    public ResponseData downloadFiles() {
    	
    	 //过滤删除的信息
    	 BizDownloadFileParam bizDownloadFileParam = new BizDownloadFileParam();
    	 
    	 //判断用户角色司机用户只能获取自己相关的记录
    	 //获取当前用户角色列表
//         LoginUser user = LoginContextHolder.getContext().getUser();
//         List<Long> roleList = user.getRoleList();

         bizDownloadFileParam.setIdNotNull(true);
         List<BizDownloadFileResult>  files = bizDownloadFileService.findListBySpec2(bizDownloadFileParam);
    	 
        return ResponseData.success(files);
    }
	
    
    /**
     * 查询所有的下载文件
     *
     * @author zjj
     * @Date 2020-08-13
     */
    @ResponseBody
    @RequestMapping("/cmsArticle")
    public ResponseData cmsArticle() {
    	
    	 //过滤删除的信息
    	 CmsArticleParam cmsArticleParam = new CmsArticleParam();
    	 
    	 cmsArticleParam.setIdNotNull(true);
    	 List<Map<String,Object>>  articles = cmsArticleService.findMapListBySpec(cmsArticleParam);
    	 
    	 List<Map<String,Object>>  articlesWrapped = new CmsArticleWrapper(articles).wrap();
    	 
         
    	 return ResponseData.success(articlesWrapped);
    }
	
    
    /**
     * 查询所有的下载文件
     *
     * @author zjj
     * @Date 2020-08-13
     */
    @ResponseBody
    @RequestMapping("/inBlackList")
    public ResponseData inBlackList(String carNum) {
    	HashMap<String, Object> result = new HashMap<>();
    	
    	boolean inBlackList = false;
    	
    	result.put("inBlackList", inBlackList);
    	
    	BizBlacklistParam param = new BizBlacklistParam();
    	
    	param.setCategory(0);  //申请黑明白
    	param.setCarNum(carNum);
    	param.setStatus(1);    //生效
    	
    	BizBlacklistResult blcak = bizBlacklistService.findBySpec(param);
    	if(blcak!=null) {
    		log.info("黑名单车辆: {}",carNum);
    		
    		inBlackList = true;
    		result.put("inBlackList", inBlackList);
    	}
         
    	return ResponseData.success(result);
    }
	
}
